import { omit } from 'lodash-es';
import { ApiClassDecorator, ApiMethodDecorator } from '../common/decorator';
import { UploadFileParams } from '/#/axios';
import { ContentTypeEnum } from '/@/enums/httpEnum';
import { defHttp } from '/@/utils/http/axios';

@ApiClassDecorator('/sys/upload')
export default class UploadApi {
  constructor(protected axios = defHttp) {}

  @ApiMethodDecorator('post')
  create(params: UploadFileParams) {
    const formData = new window.FormData();
    params.data = { type: 'image' };

    if (params.data) {
      Object.keys(params.data).forEach((key) => {
        if (!params.data) return;
        const value = params.data[key];
        if (Array.isArray(value)) {
          value.forEach((item) => {
            formData.append(`${key}[]`, item);
          });
          return;
        }

        formData.append(key, params.data[key]);
      });
    }
    // formData.append('file', params.file);
    formData.append(params.name || 'file', params.file, params.filename);
    const customParams = omit(params, 'file', 'filename', 'file');

    Object.keys(customParams).forEach((key) => {
      formData.append(key, customParams[key]);
    });
    return defHttp.post({
      url: this.path,
      params: formData,
      headers: {
        'Content-type': ContentTypeEnum.FORM_DATA,
        ignoreCancelToken: true,
      },
    });
  }
}
